/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.thu.laud.objectstore.fieldmanager;

import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.datanucleus.exceptions.NucleusDataStoreException;
import cn.edu.thu.laud.objectstore.CassandraConsistency;
import cn.edu.thu.laud.utils.serde.ConverterContext;


/**
 * Object for writing collection columns
 * 
 * @author zhuoan
 * 
 */
public class ReadMap extends ExternalEntity implements Iterable<KVEntry>,
		Iterator<KVEntry> {

	private Class<?> keyClass;

	private Class<?> valueClass;

	private int index = -1;

	private List<ColumnOrSuperColumn> columns;

	public ReadMap(Cassandra.Client client, ConverterContext context, String ownerColumnFamily,
			ByteBuffer rowKey, ByteBuffer ownerColumn, Class<?> keyClass,
			Class<?> valueClass) {
		super(client, context, ownerColumnFamily, rowKey, ownerColumn);
		this.keyClass = keyClass;
		this.valueClass = valueClass;
	}

	/**
	 * Get the slice predicate for selecting all the columns from the given
	 * start key (inclusive). If the key is null, the range reads from the
	 * beginning. Reads up to the max for the given column from start using
	 * count.
	 * 
	 * @param count
	 * @param startKey
	 * @return
	 */
	public void fetchColumns(int count, ByteBuffer startKey) {

		SliceRange range = new SliceRange();
        byte[] ownerColBytes = ByteBufferUtil.getArray(ownerColumn);
		int length = ownerColBytes.length + 1;

		if (startKey != null) {
			length += startKey.remaining();
		}

		ByteBuffer startBuff = ByteBuffer.allocate(length);
		startBuff.mark();
		startBuff.put(ownerColBytes);
		startBuff.put(DELIM_MIN);

		if (startKey != null) {
			startBuff.put(ByteBufferUtil.getArray(startKey));
		}

		startBuff.reset();

		range.setStart(startBuff);

		ByteBuffer endBuff = ByteBuffer.allocate(ownerColBytes.length + 1);
		endBuff.mark();
		endBuff.put(ownerColBytes);
		endBuff.put(DELIM_MAX);
		endBuff.reset();

		range.setFinish(endBuff);
		range.setCount(count);

		SlicePredicate predicate = new SlicePredicate();

		predicate.setSlice_range(range);

		try {
			columns = client.get_slice(rowKey, new ColumnParent(ownerColumnFamily),
					predicate, CassandraConsistency.get());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new NucleusDataStoreException(e.getMessage(), e);
		} 

	}

	public int getColumnCount() {
		return columns == null ? 0 : columns.size();
	}

	@Override
	public Iterator<KVEntry> iterator() {
		return this;
	}

	@Override
	public boolean hasNext() {
		return columns != null && index + 1 < columns.size();
	}

	/**
	 * Returns the bytes as an object identity
	 */
	@Override
	public KVEntry next() {
		if (++index > columns.size()) {
			throw new NoSuchElementException("No elements left");
		}

		Column col = columns.get(index).getColumn();

		ByteBuffer buffer = col.name;
		buffer.position(buffer.position() + ownerColumn.remaining() + 1);

		Object key = converterContext.getObject(buffer, keyClass);

		Object value = converterContext.getObject(col.value, valueClass);

		return new KVEntry(key, value);

	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("remove isn't supported");
	}

}
